package com.epam.qanda.db.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.epam.qanda.db.ConnectionManager;
import com.epam.qanda.db.dao.BaseDao;
import com.epam.qanda.db.mapping.Converter;
import com.epam.qanda.db.model.User;
import com.epam.qanda.hash.MD5;

public class UserDao implements BaseDao {
	private final String ADD_USER = "INSERT INTO user (role_id,fname,lname,login,password,email,photo,confirmation_status,rating,status,date_ban_off,hash) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)";
	private final String REMOVE_USER = "DELETE FROM user WHERE id = ?";
	private final String GET_BY_ID = "SELECT * FROM user WHERE id = ?";
	private final String GET_BY_HASH = "SELECT * FROM user WHERE hash = ?";
	private final String UPDATE_USER = "UPDATE user SET role_id=?, fname=?,lname=?, login=?, password=?, email=?, photo=?, confirmation_status=?, rating=?, status=?, date_ban_off=?  WHERE id = ?";
	private final String UPDATE_USER_ROLE_ID = "UPDATE user SET role_id=? WHERE id = ?";

	private final String GET_USER_BY_EMAIL = "SELECT * FROM user WHERE email = ?";
	private final String GET_USER_BY_LOGIN = "SELECT * FROM user WHERE login = ?";
	private final String GET_USER_BY_LOGIN_AND_PASSWORD = "SELECT * FROM user WHERE login = ? AND password = ?";
	private final String GET_ALL_USERS = "SELECT * FROM user";
	private final String GET_ALL_BANED_USRES = "SELECT * FROM user WHERE status=true AND date_ban_off IS NOT NULL and date_ban_off <= CURDATE()";
	private static final Logger LOG = Logger.getLogger("stdout");

	@Override
	public <T> void create(T element) {

		User temp = (User) element;
		Connection connection = ConnectionManager.getInstance().getConnection();
		try (PreparedStatement preparedStatement = connection.prepareStatement(ADD_USER)) {
			preparedStatement.setInt(1, temp.getRoleId());
			preparedStatement.setString(2, temp.getfName());
			preparedStatement.setString(3, temp.getlName());
			preparedStatement.setString(4, temp.getLogin());
			preparedStatement.setString(5, temp.getPassword());
			preparedStatement.setString(6, temp.getEmail());
			preparedStatement.setString(7, temp.getPhoto());
			preparedStatement.setBoolean(8, temp.isConfirmationStatus());
			preparedStatement.setInt(9, temp.getRating());
			preparedStatement.setBoolean(10, temp.isStatus());
			preparedStatement.setDate(11, temp.getDateBanOff());
			preparedStatement.setString(12,MD5.getHash(temp.getLogin()+temp.getPassword()));
			preparedStatement.executeUpdate();
			LOG.info("User created");
		} catch (SQLException e) {
			LOG.warn("smth wrong " + e.getMessage());
			throw new RuntimeException(e);
		} finally {
			ConnectionManager.getInstance().release(connection);
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public <T> T read(Integer id) {
		Connection connection = ConnectionManager.getInstance().getConnection();
		User user = null;
		try (PreparedStatement statement = connection.prepareStatement(GET_BY_ID)) {
			statement.setInt(1, id);
			ResultSet rs = statement.executeQuery();
			if (rs.next())
				user = Converter.<User> fromResaultSetToObject(rs, User.class);
		} catch (SQLException e) {
			LOG.warn("smth wrong " + e.getMessage());
		} finally {
			ConnectionManager.getInstance().release(connection);
		}
		return (T) user;
	}

	@Override
	public void delete(Integer id) {
		Connection connection = ConnectionManager.getInstance().getConnection();
		try (PreparedStatement preparedStatement = connection.prepareStatement(REMOVE_USER)) {
			preparedStatement.setInt(1, id);
			preparedStatement.executeUpdate();
			LOG.info("User deleted");
		} catch (SQLException e) {
			LOG.warn("smth wrong " + e.getMessage());
		} finally {
			ConnectionManager.getInstance().release(connection);
		}
	}

	@Override
	public <T> void update(T element) {
		User temp = (User) element;
		Connection connection = ConnectionManager.getInstance().getConnection();
		try (PreparedStatement preparedStatement = connection.prepareStatement(UPDATE_USER)) {
			preparedStatement.setInt(1, temp.getRoleId());
			preparedStatement.setString(2, temp.getfName());
			preparedStatement.setString(3, temp.getlName());
			preparedStatement.setString(4, temp.getLogin());
			preparedStatement.setString(5, temp.getPassword());
			preparedStatement.setString(6, temp.getEmail());
			preparedStatement.setString(7, temp.getPhoto());
			preparedStatement.setBoolean(8, temp.isConfirmationStatus());
			preparedStatement.setInt(9, temp.getRating());
			preparedStatement.setBoolean(10, temp.isStatus());
			preparedStatement.setDate(11, temp.getDateBanOff());
			preparedStatement.setInt(12, temp.getId());
			preparedStatement.executeUpdate();
			LOG.info("User updated");
		} catch (SQLException e) {
			LOG.warn("smth wrong " + e.getMessage());
		} finally {
			ConnectionManager.getInstance().release(connection);
		}
	}

	@SuppressWarnings("unchecked")
	public <T> T getUserByLogin(String login) {
		Connection connection = ConnectionManager.getInstance().getConnection();
		User user = null;
		try (PreparedStatement statement = connection.prepareStatement(GET_USER_BY_LOGIN)) {
			statement.setString(1, login);
			ResultSet rs = statement.executeQuery();
			if (rs.next())
				user = Converter.<User> fromResaultSetToObject(rs, User.class);
		} catch (SQLException e) {
			LOG.warn("smth wrong " + e.getMessage());
		} finally {
			ConnectionManager.getInstance().release(connection);
		}
		return (T) user;
	}

	@SuppressWarnings("unchecked")
	public <T> T getUserByEmail(String email) {
		Connection connection = ConnectionManager.getInstance().getConnection();
		User user = null;
		try (PreparedStatement statement = connection.prepareStatement(GET_USER_BY_EMAIL)) {
			statement.setString(1, email);
			ResultSet rs = statement.executeQuery();
			if (rs.next())
				user = Converter.<User> fromResaultSetToObject(rs, User.class);
		} catch (SQLException e) {
			LOG.warn("smth wrong " + e.getMessage());
		} finally {
			ConnectionManager.getInstance().release(connection);
		}
		return (T) user;
	}

	@SuppressWarnings("unchecked")
	public <T> T getUserByLoginAndPassword(String login, String password) {
		Connection connection = ConnectionManager.getInstance().getConnection();
		User user = null;
		try (PreparedStatement statement = connection
				.prepareStatement(GET_USER_BY_LOGIN_AND_PASSWORD)) {
			statement.setString(1, login);
			statement.setString(2, password);
			ResultSet rs = statement.executeQuery();
			if (rs.next())
				user = Converter.<User> fromResaultSetToObject(rs, User.class);
		} catch (SQLException e) {
			LOG.warn("smth wrong " + e.getMessage());
		} finally {
			ConnectionManager.getInstance().release(connection);
		}
		return (T) user;
	}

	@SuppressWarnings("unchecked")
	public <T> T getAllUsers() {
		Connection connection = ConnectionManager.getInstance().getConnection();
		List<User> users = new ArrayList<User>();
		try (PreparedStatement statement = connection.prepareStatement(GET_ALL_USERS)) {
			ResultSet rs = statement.executeQuery();
			while (rs.next()) {
				users.add(Converter.<User> fromResaultSetToObject(rs, User.class));
			}
		} catch (SQLException e) {
			LOG.warn("smth wrong " + e.getMessage());
		} finally {
			ConnectionManager.getInstance().release(connection);
		}
		return (T) users;
	}

	public <T> void changeRole(int id, int roleId) {
		// User temp = (User) element;
		Connection connection = ConnectionManager.getInstance().getConnection();
		try (PreparedStatement preparedStatement = connection.prepareStatement(UPDATE_USER_ROLE_ID)) {
			preparedStatement.setInt(1, roleId);
			preparedStatement.setInt(2, id);
			preparedStatement.executeUpdate();
		} catch (SQLException e) {
			LOG.warn("smth wrong " + e.getMessage());
		} finally {
			ConnectionManager.getInstance().release(connection);
		}
	}

	@SuppressWarnings("unchecked")
	public <T> T getAllBanedUsers() {
		Connection connection = ConnectionManager.getInstance().getConnection();
		List<User> users = new ArrayList<User>();
		try (PreparedStatement statement = connection.prepareStatement(GET_ALL_BANED_USRES)) {
			ResultSet rs = statement.executeQuery();
			while (rs.next()) {
				users.add(Converter.<User> fromResaultSetToObject(rs, User.class));
			}
		} catch (SQLException e) {
			LOG.warn("smth wrong " + e.getMessage());
		} finally {
			ConnectionManager.getInstance().release(connection);
		}
		return (T) users;
	}

	@SuppressWarnings("unchecked")
	public <T> T getUserByHash(String hash) {
		
			Connection connection = ConnectionManager.getInstance().getConnection();
			User user = null;
			try (PreparedStatement statement = connection.prepareStatement(GET_BY_HASH)) {
				statement.setString(1, hash);
				ResultSet rs = statement.executeQuery();
				if (rs.next())
					user = Converter.<User> fromResaultSetToObject(rs, User.class);
			} catch (SQLException e) {
				LOG.warn("smth wrong " + e.getMessage());
			} finally {
				ConnectionManager.getInstance().release(connection);
			}
			return (T) user;
	}

}
